<?php
use yii\helpers\Url;

$web = Url::base();

?>

<script type="application/javascript">

    var isRefresh = 0;
    var insSelect2;  //父机构下拉
    var rate = 1;  //汇率
    $(function ($) {
        loading.hide();

        if ("<?= $institution ?>" != 0) {
            $(".childNod").css("display", "none");
        } else {
            $("#parentSearch").css("display", "block");
            $("#status").attr("class", "col-sm-4");
        }
        if ("<?= $filter ?>" == 0) {
            $('#search1').val("");
        } else {
            $('#search1').val("<?= $filter ?>");
        }


        //主页面机构下拉列表内容初始化
        var institution =  <?= json_encode($institutionList) ?>;
        insSelect2 = $('#search2').treeAutocomplete({
            defaultText: '----请选择父级机构----',
            source: institution
        });
        //选择查询过滤的机构
        insSelect2.setValue("<?= $filterParent ?>");

        $("#select1").val("<?= $status ?>");

        $('#contacterModal').on('show.bs.modal', function (e) {
            $("#contacter_container").html('正在加载数据....');
            var institutionCode = e.relatedTarget.attributes['data-institution-code'].value;
            requestHtml('institution-contacter-partial', {institutionCode: institutionCode}, true, function (responseHtml) {
                $("#contacter_container").html(responseHtml);
            });
        });

    });

    //新增修改机构
    function addModifyInstitution(code, parentCode) {
        $("#addInstitution").modal('show');
        $("#alert1").css("display", "none");
        $("#alert2").css("display", "none");
        $("#alert3").css("display", "none");
        var data = {};
        data.institutionCode = code;
        data.parentCode = parentCode;

        requestJson("institution-detail-handler", data, true, function (re) {
            $("#parentCode").val(re.data.record.parentCode);
            $("#institutionName_Parent").val(re.data.record.parentName + '————' + re.data.record.parentCode);
            $("#code").val(re.data.record.code);

            $(".ins-info").remove();
            if (re.data.record.ins_info) {
                if (re.data.record.ins_info != "" && re.data.record.ins_info != "[]") {
                    var ins_info = JSON.parse(re.data.record.ins_info);
                    for (var key in ins_info) {
                        var v = ins_info[key];
                        var html = "";
                        html += '<div class="form-group ins-info">';
                        html += '<label class="col-lg-2 col-sm-3 control-label">' + key + '</label>';
                        html += '<div class="col-lg-10">';
                        html += '<input type="text" class="form-control" value="' + v + '">';
                        html += '</div>';
                        html += '</div>';
                        $("#salesmanPhone").parent().parent().parent().append(html);
                    }
                }
            }


            //编辑机构
            if (code) {
                $("#institutionName").attr("disabled", true);
                $("#integralRate").attr("disabled", true);
            }
            else {
                $("#institutionName").attr("disabled", false);
                $("#integralRate").attr("disabled", false);
            }
            $("#institutionName").val(re.data.record.name);
            $("#institutionAddress").val(re.data.record.address);
            if (re.data.record.isAutoOrder == 0) {
                //$("#isAutoOrder").prop("checked", true);
                $("#isAutoOrder").bootstrapSwitch('state', true);
            } else {
                //$("#isAutoOrder").prop("checked", false);
                $("#isAutoOrder").bootstrapSwitch('state', false);
            }
            if (re.data.record.isCashOrder == 1) {
                $("#isCashOrder").bootstrapSwitch('state', true);
            } else {
                $("#isCashOrder").bootstrapSwitch('state', false);
            }
            if (re.data.record.isAllowImportOrder == 1) {
                $("#isAllowImportOrder").bootstrapSwitch('state', true);
            } else {
                $("#isAllowImportOrder").bootstrapSwitch('state', false);
            }
            if (re.data.record.billModel == 1) {
                //$("#ForOrder").attr("checked", true);
                //$("#ForSend").removeAttr("checked");
                $("#ForOrder").iCheck('check');
                $("#ForSend").iCheck('uncheck');
            } else {
                //$("#ForSend").attr("checked", true);
                //$("#ForOrder").removeAttr("checked");
                $("#ForOrder").iCheck('uncheck');
                $("#ForSend").iCheck('check');
            }
            if(re.data.record.isCustomPrice==1){
                $('#isCustomPrice').bootstrapSwitch('state', true);
            }else{
                $('#isCustomPrice').bootstrapSwitch('state', false);
            }
            if (re.data.record.isEnabled == 1) {
                $('#isEnabled').bootstrapSwitch('state', true);
            } else {
                $('#isEnabled').bootstrapSwitch('state', false);
            }

            $("#integralRate").val(parseFloat(re.data.record.integralRate));
            $("#integralUnit").val(re.data.record.integralUnit);
            $("#remark").val(re.data.record.remark);
            $("#siteName").val(re.data.record.siteName);
            $("#domain").val(re.data.record.domain);

            $("#m_theme").val(re.data.record.themeM);

            //清除子元素重新描绘
            $("#themePc").empty();
            $("#themeM").empty();
            //pc端模板加载
            $.each(re.data.template_pc, function (i, item) {
                var text;
                if ((i == 0 & re.data.record.themePc == null) || re.data.record.themePc == item.img_url) {
                    text = '<div class="pc item active"> <img src=' + item.img_url + ' class="img-responsive" alt="Responsive image"> </div>';

                } else {
                    text = '<div class="pc item"> <img src=' + item.img_url + ' class="img-responsive" alt="Responsive image"> </div>';
                }
                $("#themePc").append(text);
            });

            //触屏端模板加载
            $.each(re.data.template_m, function (i, item) {
                var text;
                if ((i == 0 & re.data.record.themeM == null) || re.data.record.themeM == item.img_url) {
                    text = '<div class="m item active"> <img src=' + item.img_url + ' class="img-responsive" alt="Responsive image"> </div>';

                } else {
                    text = '<div class="m item"> <img src=' + item.img_url + ' class="img-responsive" alt="Responsive image"> </div>';
                }
                $("#themeM").append(text);
            });

            //$("#account").val(re.data.record.account);
            //$("#token").val(re.data.record.token);
            $("#salesmanName").val(re.data.record.salesmanName);
            $("#salesmanPhone").val(re.data.record.salesmanPhone);
        });
    }

    //新增或修改机构提交
    function addConfirm() {
        var data = {};
        data.institutionCode = $("#code").val();
        data.parentCode = $("#parentCode").val();
        data.name = $("#institutionName").val();
        data.address = $("#institutionAddress").val();
        data.integralRate = $("#integralRate").val();
        if (data.name == "") {
            $("#alert1").css("display", "block");
        } else if (data.address == "") {
            $("#alert2").css("display", "block");
        } else if (data.integralRate > 100000) {
            $("#alert3").css("display", "block");
        } else {

            if ($("#isEnabled").is(':checked') == true) {
                data.isEnabled = 1;
            } else {
                data.isEnabled = 0;
            }
            if ($("#isAutoOrder").is(':checked') == true) {
                data.isAutoOrder = 0;
            } else {
                data.isAutoOrder = 1;
            }
            if ($("#isCashOrder").is(':checked') == true) {
                data.isCashOrder = 1;
            } else {
                data.isCashOrder = 0;
            }
            if ($("#isAllowImportOrder").is(':checked') == true) {
                data.isAllowImportOrder = 1;
            } else {
                data.isAllowImportOrder = 0;
            }
            if ($("#ForOrder").is(':checked') == true) {
                data.billModel = 1;
            } else {
                data.billModel = 2;
            }

            if($('#isCustomPrice').is(':checked') == true){
                data.isCustomPrice=1;
            }else{
                data.isCustomPrice=0;
            }

            data.integralUnit = $("#integralUnit").val();
            data.remark = $("#remark").val();
            data.siteName = $("#siteName").val();
            data.domain = $("#domain").val();
            data.themePc = $('#pc_theme').find('.selected').attr('data-theme');
            data.themeM = $('#m_theme').val();
            //data.account = $("#account").val();
            //data.token = $("#token").val();
            data.salesmanName = $('#salesmanName').val();
            data.salesmanPhone = $('#salesmanPhone').val();
            isRefresh = data.code;
            requestJson("add-institution-handler", data, true, function (re) {
                if (re.status == 0) {
                    //$("#message").text('操作成功！');
                    alert('操作成功！');
                    refresh();
                } else {
                    //$("#message").text('操作失败！');
                    alert('操作失败！');
                }
                //$("#institutionModal3").modal('show');

            });
        }

    }

    //变更机构启用状态
    function modifyStatus(code) {
        var data = {};
        data.institutionCode = code;
        requestJson("modify-status-handler", data, true, function (re) {
            if (re.message == 0) {
                alert('操作成功！');
                isRefresh = 1;
                refresh();
            } else {
                alert('操作失败！');
            }
            //$("#institutionModal3").modal('show');
            //location.reload();

        });
    }

    //搜索
    function search() {
        var status = $("#select1").val();
        /*var filter;
         var filterP;*/
        var f = $('#search1').val()._trim();
        var fp = $('#search2').val()._trim();
        var href = window.location.href;
        var index = href.indexOf("?");
        if (index > 0) {
            href = href.substr(0, index);
        }
        if (f != '') {
            href = setUrlParam(href, 'filter', f);
        }
        if (fp != '') {
            href = setUrlParam(href, 'filterP', fp);
        }
        if (status != 99) {
            href = setUrlParam(href, 'status', status);
        }
        window.location.href = href;
        loading.show();
    }

    //刷新页面
    function refresh() {
        loading.show();
        if (isRefresh != 0) {
            location.reload();
        } else {
            var href = window.location.href;
            var index = href.indexOf("?");
            if (index > 0) {
                href = href.substr(0, index);
            }
            window.location.href = href;
        }
        isRefresh = 0;
    }

    function resetRate() {
        if ($('#integralRate').val() > 100000) {
            $('#integralRate').val(rate);
        } else {
            rate = $('#integralRate').val();
        }
    }

    //导出机构
    function exportInstitution() {

        var data = {};

        data.status = $("#select1").val();

        var f = $('#search1').val()._trim();
        if (f == '') {
            data.filter = 0;
        } else {
            data.filter = f;
        }
        var fp = $('#search2').val()._trim();
        if (fp == '') {
            data.filterP = 0;
        } else {
            data.filterP = fp;
        }
        var result = requestJson("export-institution-list-handler", data);
        fileName = "<?= $web ?>/" + result.data;
        $("#export-excel-download").attr("href", fileName);
    }

</script>

<div class="panel panel-default">
    <div class="panel-body">
        <div class="form-inline">
            <div class="btn-group">
                <button class="btn btn-default " type="button" onclick="addModifyInstitution(0,'<?= $institution ?>')">
                    <i class="fa fa-plus"></i> 新增机构
                </button>

            </div>
            <div class="btn btn-default" type="button" id="exportUserIntegral" onclick="exportInstitution()">
                <i class="glyphicon glyphicon-download-alt"></i>
                <a id="export-excel-download" href="<?= $web ?>/exportInstitutionDemo.xlsx">导出机构</a>
            </div>

            <div class="pull-right">
                <div class="form-group">
                    <div id="parentSearch" style="display: none">
                        <div id="search2"></div>

                    </div>
                </div>
                <div class="form-group">
                    <div id="status">
                        <select class="form-control" id="select1">
                            <option value="99">状态</option>
                            <option value="1">启用</option>
                            <option value="0">禁用</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <input type="text" class="form-control" id="search1" placeholder="请输入机构名称或编码"
                           onkeypress="if(event.keyCode==13) {search();return false;}">
                </div>
                <div class="btn-group">
                    <button type="button" class="btn btn-primary" onclick="search()"><i class="fa fa-search"></i> 搜索
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="panel">
    <div class="panel-body">
        <div class="table-responsive">
            <table class="table table-bordered table-hover table-condensed"
                   id="institutionTable">
                <thead>
                <tr class="nowrap">
                    <th class="col-lg-1">机构编码</th>
                    <th class="col-lg-4">机构名称</th>
                    <th>上级机构</th>
                    <th>订单是否审核</th>
                    <th>结算方式</th>
                    <th>汇率</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <?php
                for ($i = 0; $i < count($record); $i++) {
                    ?>
                    <tr>
                        <td><?= $record[$i]['code'] ?></td>
                        <td><?= $record[$i]['name'] ?></td>
                        <td><?= $record[$i]['parentName'] ?></td>
                        <td><?= $record[$i]['isAutoOrder'] ?></td>
                        <td class="nowrap"><?= $record[$i]['billModel'] ?></td>
                        <td class="nowrap">
                            1元=<?= doubleval($record[$i]['integralRate']) ?><?= $record[$i]['integralUnit'] ?></td>
                        <td><?php if ($record[$i]['isEnabled'] == 1) {
                                echo '<span class="label label-success">启用</span>';
                            } else {
                                echo '<span class="label label-danger">禁用</span>';
                            } ?>
                        <td>
                            <button class="btn btn-link btn-xs" type="button"
                                    onclick="addModifyInstitution('<?= $record[$i]['code'] ?>','<?= $record[$i]['parentCode'] ?>')">
                                修改
                            </button>
                            <button class="btn btn-link btn-xs" type="button"
                                    onclick="modifyStatus('<?= $record[$i]['code'] ?>')">
                                <?php if ($record[$i]['isEnabled'] == '1') {
                                    echo '禁用';
                                } else {
                                    echo '启用';
                                } ?>
                            </button>
                            <a class="btn btn btn-link btn-xs" type="button" data-toggle="modal" href="#contacterModal"
                               data-institution-code="<?= $record[$i]['code'] ?>">联系人
                            </a>
                            <button class="childNod btn btn-link btn-xs" type="button"
                                    onclick="addModifyInstitution(0,'<?= $record[$i]['code'] ?>')">新增下级机构
                            </button>
                        </td>
                    </tr>
                    <?php
                }
                ?>
                </tbody>
            </table>
        </div>
        <div class="pull-left">
            <?= \app\widgets\LinkPagerExt::widget(['pagination' => $pagination]) ?>
        </div>
    </div>
</div>

<!-- Modal GoodsDetail新增、编辑机构-->
<div aria-hidden="true" role="dialog" tabindex="-1" id="addInstitution" class="modal fade in">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
                <h4 class="modal-title">添加/编辑机构</h4>
            </div>
            <div class="modal-body">
                <div class="form-horizontal adminex-form">
                    <div class="form-group">
                        <label class="col-lg-2 col-sm-3 control-label"><span style="color: red">*</span>机构名称</label>
                        <div class="col-lg-10">
                            <input type="text" class="form-control" id="institutionName">
                            <input class="hidden_id" id="code" type="hidden" value="0"/>
                            <label id='alert1' style="display: none;"><span style="color: red">机构名称不允许为空</span></label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-2 col-sm-3 control-label">上级机构</label>
                        <div class="col-lg-10">
                            <input type="text" class="form-control" id="institutionName_Parent" placeholder="无"
                                   disabled="true">
                            <input class="hidden_id" id="parentCode" type="hidden" value="0"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-2 col-sm-3 control-label"><span style="color: red">*</span>机构地址</label>
                        <div class="col-lg-10">
                            <input type="text" class="form-control" id="institutionAddress" placeholder="">
                            <label id='alert2' style="display: none;"><span style="color: red">地址不允许为空</span></label>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2">
                            <label class="checkbox-inline">
                                <div class="switch">
                                    <input type="checkbox" id="isAutoOrder"><span
                                        class="btn-clipboard popovers" data-trigger="hover"
                                        data-placement="right"
                                        data-content="开启后，会员兑换的订单需机构管理员在后台进行确认后，才会生效。"
                                        data-original-title="提示">  订单需要审核</span>
                                </div>
                            </label>
                            <label class="checkbox-inline">
                                <div class="switch">
                                    <input type="checkbox" id="isCashOrder"><span
                                        class="btn-clipboard popovers" data-trigger="hover"
                                        data-placement="right"
                                        data-content="开启后，允许会员使用现金（现金+积分）混合支付，兑换产品。否则禁止用户使用现金。"
                                        data-original-title="提示">  支持现金支付</span>
                                </div>
                            </label>
                            <label class="checkbox-inline">
                                <div class="switch">
                                    <input type="checkbox" id="isAllowImportOrder"><span
                                        class="btn-clipboard popovers" data-trigger="hover"
                                        data-placement="right"
                                        data-content="开启后，允许机构管理员从后台批量导入兑换订单。"
                                        data-original-title="提示">  允许导入订单</span>
                                </div>
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2">
                            <label class="checkbox-inline">
                                <div class="switch">
                                    <input id="isEnabled" type="checkbox" checked/>
                                    <span>启用  </span>
                                </div>
                            </label>
                            <?php
                            $isAdmin = \app\models\Permission::isSystemAdmin();
                            $style = '';
                            if (!$isAdmin) {
                                $style = 'style="display: none"';
                            }
                            ?>
                            <label class="checkbox-inline" <?= $style ?>>
                                <div class="switch">
                                    <input type="checkbox" id="isCustomPrice"><span
                                        class="btn-clipboard popovers" data-trigger="hover"
                                        data-placement="right"
                                        data-content="开启后，允许机构自主定价。"
                                        data-original-title="提示">  允许自主定价</span>
                                </div>
                            </label>
                        </div>
                    </div>

                    <div class="form-group" <?= $style ?>>
                        <label class="col-lg-2 col-sm-3 control-label">结算方式</label>
                        <div class="col-lg-10">
                            <label class="control-label">
                                <div class="square-blue">
                                    <div class="radio">
                                        <div class="square-blue form-inline icheck">
                                            <div class="radio popovers">
                                                <input type="radio" name="optionsRadios" id="ForOrder" value="1">
                                                按订单结算
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </label>
                            <label class="control-label">
                                <div class="square-blue">
                                    <div class="radio">
                                        <div class="square-blue form-inline icheck">
                                            <div class="radio popovers">
                                                <input type="radio" name="optionsRadios" id="ForSend" value="2">
                                                按发货结算
                                            </div>
                                        </div>
                                    </div>
                                </div>

                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-2 col-sm-3 control-label">汇率</label>
                        <label class="col-sm-2 control-label">1元=</label>
                        <div class="col-sm-2">
                            <input type="number" max='100000' class="form-control" id="integralRate" value="1"
                                   onkeydown="resetRate()" onchange="resetRate()">
                        </div>
                        <div class="col-sm-2">
                            <input type="text" class="form-control" id="integralUnit" value="积分">
                        </div>
                        <label id='alert3' style="display: none;"><span style="color: red">汇率不能大于100000</span></label>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-2 col-sm-3 control-label">备注</label>
                        <div class="col-lg-10">
                            <textarea rows="6" class="form-control" id="remark"></textarea>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-2 col-sm-3 control-label">网站名称</label>
                        <div class="col-lg-10">
                            <input type="text" class="form-control" id="siteName">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-2 col-sm-3 control-label">域名</label>
                        <div class="col-lg-10" <?= $style ?>>
                            <input type="text" class="form-control" id="domain">
                        </div>
                        <?php
                        if (!$isAdmin) {
                            ?>
                            <div class="col-lg-10">
                                <label class="col-lg-7">如需域名，请联系朵拉客服，联系电话400-860-3111</label>
                            </div>
                            <?php
                        }
                        ?>

                    </div>
                    <div class="form-group" style="display: none;">
                        <label class="col-lg-2 col-sm-3 control-label">PC模板</label>
                        <div class="col-lg-10 mall-theme-select" id="pc_theme">
                            <img class="col-lg-3 selected" data-theme="" src="<?= $web ?>/images/hair-two-1.png">
                            <img class="col-lg-3" data-theme="green" src="<?= $web ?>/images/hair-two-1.png">
                            <img class="col-lg-3" data-theme="red" src="<?= $web ?>/images/hair-two-1.png">
                        </div>
                    </div>
                    <div class="form-group" <?= $style ?>>
                        <label class="col-lg-2 col-sm-3 control-label">触屏模板</label>
                        <div class="col-lg-10">
                            <input type="text" class="form-control" id="m_theme">
                        </div>

                    </div>
                    <div class="form-group" style="display: none">
                        <label class="col-lg-2 col-sm-3 control-label">接入账号</label>
                        <div class="col-lg-10">
                            <input type="text" class="form-control" id="account" placeholder="前端站点通过api接口接入系统的账号">
                        </div>
                    </div>
                    <div class="form-group" style="display: none">
                        <label class="col-lg-2 col-sm-3 control-label">TOKEN</label>
                        <div class="col-lg-10">
                            <input type="text" class="form-control" id="token" placeholder="前端站点通过api接口接入系统的token">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-2 col-sm-3 control-label">销售人员</label>
                        <div class="col-sm-2">
                            <input type="text" class="form-control" id="salesmanName" placeholder="姓名">
                        </div>
                        <div class="col-sm-2">
                            <input type="text" class="form-control" id="salesmanPhone" placeholder="电话">
                        </div>
                    </div>

                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal">关闭</button>
                <button class="btn btn-primary" onclick="addConfirm()">保存</button>
            </div>
        </div>
    </div>
</div>

<div aria-hidden="true" role="dialog" tabindex="-1" id="contacterModal" class="modal fade">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
                <h4 class="modal-title">机构联系人</h4>
            </div>
            <div class="modal-body" id="contacter_container">
                正在加载数据....
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 提示框 -->
<div aria-hidden="true" role="dialog" tabindex="-1" id="institutionModal3" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
                <h4 class="modal-title">消息</h4>
            </div>
            <div class="modal-body" id="message">
                操作失败！
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" onclick="refresh()"> Ok</button>
            </div>
        </div>
    </div>
</div>

<script type="application/javascript">
    //设置模态窗:当用户点击模态框外部时不会关闭、当初始化时不显示模态框。
    $(function () {
        $('#contacterModal').modal({
            backdrop: 'static', show: false
        });
    });
</script>
